package servlets;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.SQLException;

import contents.*;
import database.Database;

public class ApplicationServlet extends HttpServlet {
    private static String servletPath;
    
    public static String getServletPath() {
        return servletPath;
    }
    
    @Override
    public void init() {
        servletPath = getServletContext().getRealPath("");
        
        AdminContent.setInformationForTimetablesFilePath();
        FileUploadServlet.setUploadedFilePath();
    }
    
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");

        HttpSession session = request.getSession(true);
        
        if (session.getAttribute("userRole") == null) {
            // set new user as visitor
            session.setAttribute("userRole", "visitor");
        }
        
        String contentRequest = (String) request.getParameter("content");

        try {
            Database.ensureConnectionIsOpen();
            
            String userRole = (String) session.getAttribute("userRole");
            
            // check for new messages
            if (!userRole.equals("visitor")) {
                request = MessagesContent.checkForNewMessages(request);
            }
            
            if (contentRequest == null) {
                // do nothing
                
            } else if (contentRequest.equals("classesList")) {
                request = ListsContent.setClassesListContent(request);
            } else if (contentRequest.equals("showTimetable") && request.getParameter("classId") != null) {
                request = TimetablesContent.setContent(request);
                request.getRequestDispatcher("WEB-INF/jspf/timetables_contents/class_timetable.jsp").forward(request, response);
                return;
            } else if (contentRequest.equals("teachersList")) {
                request = ListsContent.setTeachersListContent(request);
            } else if (contentRequest.equals("substitutionsList")) {
                request = ListsContent.setSubstitutionsListContent(request);
            } else {
                if (userRole.equals("visitor")) {
                    if (contentRequest.equals("login")) {
                        if (LoggingContent.tryToLogIn(request)) {
                            response.sendRedirect("/gradebook/gradebook?content=loginSuccessful");
                        } else {
                            response.sendRedirect("/gradebook/gradebook?content=loginUnsuccessful");
                        }
                        return;
                    } else if (contentRequest.equals("loginUnsuccessful")) {
                        // do nothing
                    }

                } else {
                    if (contentRequest.equals("logout")) {
                        session.invalidate();
                        response.sendRedirect("/gradebook/gradebook");
                        return;
                    } else if (contentRequest.equals("changePassword")) {
                        if (LoggingContent.changePassword(request)) {
                            response.sendRedirect("/gradebook/gradebook?content=passwordChangeSuccessful");
                        } else {
                            response.sendRedirect("/gradebook/gradebook?content=passwordChangeUnsuccessful");
                        }
                        return;
                    } else if (contentRequest.equals("messageBox")) {
                        request = MessagesContent.setMessageBoxContent(request);
                    } else if (contentRequest.equals("deleteMessage")) {
                        if (MessagesContent.deleteMessage(request)) {
                            // what kind of sort was used
                            String sortType = request.getParameter("sort");
                            if (sortType == null || sortType.equals("byDate")) {
                                response.sendRedirect("/gradebook/gradebook?content=messageBox");
                            } else {
                                response.sendRedirect("/gradebook/gradebook?content=messageBox&sort=alphabetically");
                            }
                            return;
                        } else {
                            response.sendError(HttpServletResponse.SC_NOT_FOUND);
                            return;
                        }
                    } else if (contentRequest.equals("writeNewMessage")) {
                        request = MessagesContent.setNewMessageContent(request);
                    } else if (contentRequest.equals("sendMessage")) {
                        if (MessagesContent.sendMessage(request)) {
                            response.sendRedirect("/gradebook/gradebook?content=messageBox");
                        } else {
                            response.sendError(HttpServletResponse.SC_NOT_FOUND);
                        }
                        return;
                    } else {
                        if (userRole.equals("admin")) {
                            request = AdminContent.setContent(request);
                            if (contentRequest.equals("deleteAbsence")) {
                                response.sendRedirect("/gradebook/gradebook?content=absences");
                                return;
                            } else if (contentRequest.equals("addAbsence") ||
                                    contentRequest.equals("addSubject") || contentRequest.equals("editSubject") ||
                                    contentRequest.equals("addClass") || contentRequest.equals("editClass") || 
                                    contentRequest.equals("deleteClass") ||
                                    contentRequest.equals("addTeacher") || contentRequest.equals("editTeacher") ||
                                    contentRequest.equals("newPasswordForTeacher") ||
                                    contentRequest.equals("addStudent") || contentRequest.equals("editStudent") ||
                                    contentRequest.equals("newPasswordForStudent") || contentRequest.equals("newPasswordForParent") ||
                                    contentRequest.equals("setTimetable")) {
                                String resultAttribute = (String)request.getAttribute("result");
                                if (resultAttribute != null && resultAttribute.equals("failed")) {
                                    String action = (String) request.getAttribute("action");
                                    response.sendRedirect("/gradebook/gradebook?content=actionFailed&action=" + action);
                                } else {
                                    String redirect = (String) request.getAttribute("redirect");
                                    response.sendRedirect("/gradebook/gradebook?content=" + redirect);
                                }
                                return;
                            } else if (contentRequest.equals("deleteSubject")) {
                                response.sendRedirect("/gradebook/gradebook?content=subjects");
                                return;
                            } else if (contentRequest.equals("deleteTeacher")) {
                                response.sendRedirect("/gradebook/gradebook?content=teachers");
                                return;
                            } else if (contentRequest.equals("deleteStudent")) {
                                response.sendRedirect("/gradebook/gradebook?content=students");
                                return;
                            } else if (contentRequest.equals("downloadXMLInformationForTimetables")) {
                                response = AdminContent.setInformationForTimetablesFileDownloadResponse(response);
                                return;
                            } else if (contentRequest.equals("deleteTimetable")) {
                                response.sendRedirect("/gradebook/gradebook?content=timetables");
                                return;
                            } else if (contentRequest.equals("deleteSubstitution") || contentRequest.equals("setSubstitution")) {
                                response.sendRedirect("/gradebook/gradebook?content=substitutions");
                                return;
                            }
                            
                        } else if (userRole.equals("student")) {
                            request = StudentContent.setContent(request);
                            if (contentRequest.equals("deleteTutorage")) {
                                String redirectTo = request.getParameter("redirectTo");
                                if (redirectTo.equals("all")) {
                                    response.sendRedirect("/gradebook/gradebook?content=allTutorages");
                                } else {
                                    response.sendRedirect("/gradebook/gradebook?content=myTutorages");
                                }
                                return;
                            } else if (contentRequest.equals("addTutorage")) {
                                response.sendRedirect("/gradebook/gradebook?content=myTutorages");
                                return;
                            }
                            
                        } else if (userRole.equals("parent")) {
                            request = ParentContent.setContent(request);
                            
                        } else if (userRole.equals("teacher")) {
                            request = TeacherContent.setContent(request);
                            if (contentRequest.equals("showTimetable")) {
                                request = TimetablesContent.setContent(request);
                                request.getRequestDispatcher("WEB-INF/jspf/timetables_contents/teacher_timetable.jsp").forward(request, response);
                                return;
                            } else if (contentRequest.equals("deleteNotice") || contentRequest.equals("addNotice")) {
                                int classId = Integer.valueOf(request.getParameter("classId"));
                                response.sendRedirect("/gradebook/gradebook?content=noticeboards&classId=" + classId);
                                return;
                            } else if (contentRequest.equals("saveGrades")) {
                                response.sendRedirect("/gradebook/gradebook?content=grades");
                                return;
                            } else if (contentRequest.equals("deleteAbsence")) {
                                response.sendRedirect("/gradebook/gradebook?content=reportAbsence");
                                return;
                            } else if (contentRequest.equals("addAbsence")) {
                                if (request.getAttribute("result") == null) {
                                    response.sendRedirect("/gradebook/gradebook?content=reportAbsence");
                                } else {
                                    response.sendRedirect("/gradebook/gradebook?content=addAbsenceFailed");
                                }
                                return;
                            }
                            
                        } else {
                            System.err.println("Unknown content request: " + contentRequest);
                            
                            // Send 404 error code.
                            response.sendError(HttpServletResponse.SC_NOT_FOUND);
                            return;
                        }
                    }
                }
            }

            request.getRequestDispatcher("WEB-INF/jspf/page_frame.jsp").forward(request, response);
        } catch (SQLException exception) {
            System.err.println("Exception occured during querying the database: " + exception.getMessage());
            exception.printStackTrace();
                    
            // Send 404 error code.
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        } catch (Exception exception) {
            System.err.println("Exception occured during processing the query: " + exception.getMessage());
            exception.printStackTrace();
                    
            // Send 404 error code.
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
    }
}
